import {Text, View, StyleSheet} from 'react-native';
import React, {useState, useEffect, useRef} from 'react';

export default function 作业_rn计数器6_9() {
  const [count, setCount] = useState(0);
  const countRef = useRef(count);
  useEffect(() => {
    countRef.current = count; // 在这里更新引用
    console.log(
      '🚀 ~ file: 6_9作业_rn计数器.jsx:9 ~ useEffect ~ count:',
      count,
    );
  }, [count]);

  useEffect(() => {
    let timer = setInterval(() => {
      // console.log(count, countRef.current);
      if (countRef.current >= 3) {
        return clearInterval(timer);
      }
      setCount(oldVal => {
        // console.log(oldVal);
        return oldVal + 1;
      });
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <View style={styles.root}>
      <Text style={styles.titleTxt}>RN计数器</Text>
      <Text style={styles.countTxt}>{count}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  root: {
    width: '100%',
    height: 500,
    backgroundColor: '#353535',
    flexDirection: 'column',
    alignItems: 'center',
  },
  titleTxt: {
    marginTop: 96,
    fontSize: 36,
    fontWeight: 'bold',
    color: 'white',
  },
  countTxt: {
    marginTop: 64,
    fontSize: 96,
    fontWeight: 'bold',
    color: '#1876ff',
  },
});
